import AVFoundation
import Flutter

class SpeechPlayer {
    private static var mediaPlayer: AVAudioPlayer?
    private static let audioSession = AVAudioSession.sharedInstance()

    private static var _duration: TimeInterval? = 0.0
    
    static func startSpeech(filePath: String, startTime: TimeInterval, duration: TimeInterval, result:@escaping FlutterResult) {
        stopSpeech() // 停止之前的播放
        
        // 解析路径类型（远程或本地）
        let url: URL?
        let isRemote: Bool
        
        if let parsedURL = URL(string: filePath), let scheme = parsedURL.scheme?.lowercased() {
            // 检查是否为 HTTP/HTTPS 地址
            if scheme == "http" || scheme == "https" {
                isRemote = true
                url = parsedURL
            } else if scheme == "file" {
                // 直接处理 file:// 路径
                isRemote = false
                url = parsedURL
            } else {
                print("不支持的 URL 类型")
                result(-1.0)
                return
            }
        } else {
            // 视为本地路径，构造文件 URL
            isRemote = false
            url = URL(fileURLWithPath: filePath)
        }
        
        if isRemote {
            // 处理远程资源下载
            guard let remoteURL = url else {
                result(-1.0)
                return
            }
            
            let task = URLSession.shared.downloadTask(with: remoteURL) { tempURL, _, error in
                guard let tempURL = tempURL else {
                    print("下载失败: \(error?.localizedDescription ?? "未知错误")")
                    SensorUtil.shared.stopProximityMonitoring()
                    result(-1.0)
                    return
                }
                print("下载完成: \(tempURL)")
                play(tempURL: tempURL, startTime: startTime, duration: duration, result: result)
            }
            task.resume()
        } else {
            // 处理本地文件
            guard let localURL = url else {
                result(-1.0)
                return
            }
            
            // 检查文件是否存在
            var isDir: ObjCBool = false
            if FileManager.default.fileExists(atPath: localURL.path, isDirectory: &isDir), !isDir.boolValue {
                play(tempURL: localURL, startTime: startTime, duration: duration, result: result)
            } else {
                SensorUtil.shared.stopProximityMonitoring()
                print("本地文件不存在: \(localURL.path)")
                result(-1.0)
            }
        }
        
        SensorUtil.shared.startProximityMonitoring()
    }
    
    private static func play(tempURL: URL, startTime: TimeInterval,duration: TimeInterval, result: FlutterResult){
        do {
            // 配置音频会话为语音通信模式
            try audioSession.setCategory(.playAndRecord,
                                        mode: .voiceChat,
                                        options: [.defaultToSpeaker, .allowBluetooth])
            try audioSession.setActive(true)
            
            SensorUtil.shared.initSpeaker()
            
            // 创建播放器并配置
//                let url = URL(fileURLWithPath: tempURL) // 这里是播放本地文件
            mediaPlayer = try AVAudioPlayer(contentsOf: tempURL)
            mediaPlayer?.delegate = playerDelegate
            mediaPlayer?.numberOfLoops = 0 // 不循环
            
            mediaPlayer?.currentTime = startTime/1000
            
            // 开始播放
            mediaPlayer?.prepareToPlay()
            mediaPlayer?.play()

            if duration > 0 {
                _duration = duration;
                startTimer(duration: duration)
            }
            

            
//            print("\(mediaPlayer?.duration)")
            
            let data: [String: Any] = [
                "time": mediaPlayer?.duration ?? -1,
                "isSpeaker": !SensorUtil.shared.getNear()
            ]
            
            result(data)
        } catch {
            print("初始化失败: \(error.localizedDescription)")
            result(-1.0)
        }
    }
    
    static func playSeekTo(startTime: TimeInterval){
        do {

            mediaPlayer?.currentTime = startTime/1000
            
            // 开始播放
            mediaPlayer?.play()

            if let duration = _duration {
                startTimer(duration: duration)
            }
            
//            print("\(mediaPlayer?.duration)")

        } catch {
            print("初始化失败: \(error.localizedDescription)")
        }
    }
    
    
    static func pauseSpeech(result:@escaping FlutterResult) {
        if let player = mediaPlayer, player.isPlaying {
            player.pause()
            
            let currentTime = player.currentTime
            
            
            SensorUtil.shared.stopProximityMonitoring()
            
            //定时停止
            stopTimer()
            
            result(currentTime)
        }
    }
    
    static func cancelPause(){
        if let player = mediaPlayer, !player.isPlaying {
            player.play()
            
            if let duration = _duration{
                startTimer(duration: duration)
            }
        
            SensorUtil.shared.startProximityMonitoring()
        }
    }
    
    static func stopSpeech() {
        if let player = mediaPlayer {
            if player.isPlaying {
                player.stop()
            }
            //定时停止
            stopTimer()
            
            mediaPlayer = nil
            // 重置音频会话
            try? audioSession.setActive(false)
        }
        
        SensorUtil.shared.stopProximityMonitoring()
    }
    
    static func getMediaPlayer() -> AVAudioPlayer? {
        return mediaPlayer
    }
    
    
    private static var timer: Timer?

    public static func startTimer(duration: TimeInterval) {
        if duration <= 0 {
            return
        }
        stopTimer()
        
        // 使用主线程运行定时器（类似 Android 的 MainLooper）
        DispatchQueue.main.async {
            // 创建定时器（间隔自动转换为秒）
            timer = Timer.scheduledTimer(
                withTimeInterval: duration / 1000,
                repeats: true
            ) { _ in
                guard let mediaPlayer = mediaPlayer, mediaPlayer.isPlaying else {
                    return
                }
                
                // 获取当前播放位置（单位：毫秒）
                let currentTime = mediaPlayer.currentTime
                // 转换为秒并回调（假设 currentPosition 是毫秒单位）
                SpeechPlayHelper.shared.onListenerPlayTime(time: currentTime)
            }
            
            // 将定时器加入主循环（兼容滚动等场景）
            RunLoop.main.add(timer!, forMode: .common)
        }
    }

    public static func stopTimer() {
        // 主线程安全操作
        DispatchQueue.main.async {
            timer?.invalidate()
            timer = nil
        }
    }
    
    // MARK: - 播放完成委托
    private static let playerDelegate = PlayerDelegate()
    
    private class PlayerDelegate: NSObject, AVAudioPlayerDelegate {
        func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
            
            SensorUtil.shared.stopProximityMonitoring()
            SpeechPlayer.stopSpeech()
            print("播放自然结束")
            
            SpeechPlayHelper.shared.onListenerCompleted()
            
        }
    }
}
